package main

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_"github.com/go-sql-driver/mysql"
	//"fmt"
	//"strconv"
)

type Many struct{
	beego.Controller
}

type ProductType struct{
	Id int `orm:"pk;auto"`
	Name string
	//ProductList []*Product `orm:"reverse(many)"`

}

type Product struct{
	Id int `orm:"pk;auto"`
	Name string
	Type *ProductType `orm:"rel(fk)"`
	//MealList []*Meal `orm:"reverse(many)"`
}

type ProjectType struct{
	Id int `orm:"pk;auto"`
	Name string
	//ProjectList []*Project `orm:"reverse(many);type(text)"`
}

type Project struct{
	Id int `orm:"pk;auto"`
	Name string
	Type *ProjectType `orm:"rel(fk)"`
	//MealList []*Meal `orm:"reverse(many)"`

}

type Meal struct{
	Id int `orm:"pk;auto"`
	Name string
	ProjectList []*Project `orm:"rel(m2m)"`
	ProductList []*Product `orm:"rel(m2m)"`
	//Memberlist []*Member `orm:"reverse(many)"`
}

type Member struct{
	Id int `orm:"pk;auto"`
	Name string
	Meallist []*Meal `orm:"rel(m2m)"`

}

func init(){
	orm.Debug = true
	orm.RegisterDataBase("default", "mysql", "root:new_password@tcp(127.0.0.1:3306)/orm_insert?charset=utf8")
	orm.RegisterModel(new(ProductType), new(Product), new(ProjectType), new(Project), new(Meal), new(Member))
	orm.RunSyncdb("default", false, true)
	orm.SetMaxIdleConns("default", 10)
	orm.SetMaxOpenConns("default", 100)
}

func (m *Many)Favicon(){
	return
}

func (m *Many)QueryMember(){
	o := orm.NewOrm()
	var ms []*Member
	//b.Id = 2
	//o.Read(&b)
	//o.LoadRelated(&b, "UserList")
	//o.Raw("select * from blog where id = ?", 1).QueryRow(&b)
	//o.QueryTable("member").Filter("id", 1).All(&ms)
	o.QueryTable("member").All(&ms)
	for _, v := range ms{
		o.LoadRelated(v, "Meallist")
		//o.QueryTable("meal").Filter("MemberList__member__id", v.Id).All(&v.Meallist)
		for _, mv := range v.Meallist{
			o.LoadRelated(mv, "ProjectList")
			//o.LoadRelated(mv, "Memberlist")
			//o.QueryTable("project").Filter("MealList__meal__id", mv.Id).RelatedSel("Type").All(&mv.ProjectList)
			for _, jv := range mv.ProjectList{
				o.LoadRelated(jv, "Type")
				//o.LoadRelated(jv, "Meallist")
				//o.LoadRelated(jv.Type, "ProjectList")
			}

			o.LoadRelated(mv, "ProductList")
			//o.QueryTable("product").Filter("MealList__meal__id", mv.Id).All(&mv.ProductList)
			for _, dv := range mv.ProductList{
				o.LoadRelated(dv, "Type")
				//o.LoadRelated(dv, "Meallist")
				//o.LoadRelated(dv.Type, "ProductList")
			}
		}
	}

	m.Data["json"] = &ms
	m.ServeJSON()

}

func main(){
	beego.BConfig.WebConfig.Session.SessionOn = true
	beego.Router("/queryMember", &Many{},"GET:QueryMember")
	//beego.Router("/deleteMeal", &Many{},"GET:DeleteMeal")
	//beego.Router("/updateMeal", &Many{},"GET:UpdateMeal")
	beego.Router("/favicon.ico", &Many{},"*:Favicon")
	beego.Run()
}
